package com.hc.dao.bbs.impl;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.Query;

import com.hc.dao.bbs.ClubDAO;
import com.hc.dao.impl.GenericHibernateDAO;
import com.hc.entity.bbs.BBSComponent;
import com.hc.entity.bbs.Topic;
import com.hc.constants.Constant;

public class ClubDAOImpl extends GenericHibernateDAO<BBSComponent, Integer> implements ClubDAO {

	@SuppressWarnings("unchecked")
	public List<Topic> getPageByComponentId(Integer componentId, Integer pageNo) {
		List<Topic> list = null;

		Session session = getSession(); 
		Query query = session.createQuery(" from Topic topic where topic.parentId = " + componentId);
		
		query.setFirstResult((pageNo-1) + 1);
		query.setMaxResults(Constant.PAGE_SIZE);
		list = (List<Topic>) query.list();
		session.close();
		return list;
	}

	public BBSComponent getParent(Object object) {
		BBSComponent parent = null;
		if (object instanceof Topic || object instanceof BBSComponent) {
			try {
				Method method = object.getClass().getMethod("getParentId", null);
				String hql = "select b from BBSComponent b where b.componentId = " + method.invoke(object); 
				List<BBSComponent> list = getHibernateTemplate().find(hql);
				if (list.size() > 0) {
					parent = list.get(0);
				}
			} catch(NoSuchMethodException e) {
				e.printStackTrace();
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				e.printStackTrace();
			}
		}
		return parent;
	}
	
	@Override
	public int getTopicCountByComponentId(Integer componentId) {
		String hql = "select count(*) from Topic t where t.parentId = " + componentId;
		int topicCount = ((Long)getHibernateTemplate().find(hql).listIterator().next()).intValue();
		return topicCount;
	}

}
